package com.wanmait.zaisousuo.webcontroller;


import com.github.pagehelper.PageInfo;
import com.wanmait.zaisousuo.pojo.*;
import com.wanmait.zaisousuo.service.*;
import com.wanmait.zaisousuo.util.CodeUtil;
import com.wanmait.zaisousuo.util.CookieUtil;
import com.wanmait.zaisousuo.util.GetVisitTime;
import com.wanmait.zaisousuo.util.MD5Utils;
import org.apache.commons.io.FilenameUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.sql.Timestamp;
import java.util.List;
import java.util.UUID;



@Controller
@RequestMapping("/web")
public class UserinfoWebController {
    @Resource
    private AnswerService answerService;
    @Resource
    private UserinfoService userinfoService;
    @Resource
    private TextureService textureService;
    @Resource
    private ArticleService articleService;

    @Resource
    private GarbageService garbageService;
    @Resource
    private QuestionService questionService;
    @Resource
    private CityService cityService;
    @Resource
    private CompanyApprovalService companyApprovalService;
    //访问注册页面
    @RequestMapping("userinfo/register")
    public void register() {
    }

    //邮箱注册
    @PostMapping("userinfo/emailRegister")
    public String emailRegister(Userinfo userinfo) {
        String password = userinfo.getPassword();
        userinfo.setPassword(MD5Utils.md5(password));
        userinfoService.insert(userinfo);
        return "redirect:/web/userinfo/login";
    }

    //手机号注册
    @PostMapping("userinfo/phoneRegister")
    public String phoneRegister(Userinfo userinfo) {
        String password = userinfo.getPassword();
        userinfo.setPassword(MD5Utils.md5(password));
        userinfoService.insertByPhone(userinfo);
        return "redirect:/web/userinfo/login";
    }

    //访问登录页面
    @RequestMapping("userinfo/login")
    public void login(HttpServletRequest request) {
        //获取来路地址
        String path = request.getHeader("referer");
        HttpSession session = request.getSession();
        session.setAttribute("path", path);
    }

    //登录cookie
    @PostMapping("userinfo/login")
    @ResponseBody
    public String login(String username, String password, boolean RememberMe, HttpServletResponse response, HttpSession session, HttpServletRequest request) {
        Userinfo userinfo = userinfoService.login(username, MD5Utils.md5(password));
        if (userinfo != null) {
            session.setAttribute("userinfo", userinfo);

            Userinfo userinfos = new Userinfo();
            userinfos.setId(userinfo.getId());
            userinfos.setLastLoginIp(request.getRemoteAddr());
            userinfos.setLastLoginTime(Timestamp.valueOf(GetVisitTime.visitTime()));
            userinfoService.update(userinfos);
            if (RememberMe == true) {
                String email = userinfo.getEmail();
                String phone_number = userinfo.getPhoneNumber();
                String userpass = userinfo.getPassword();
                CookieUtil.addCookie("phone_number", phone_number, 60 * 60 * 24 * 7, response);
                CookieUtil.addCookie("email", email, 60 * 60 * 24 * 7, response);
                CookieUtil.addCookie("userpass", MD5Utils.mymd5(userpass), 60 * 60 * 24 * 7, response);

            }
            return "1";
        }
        else {
            return "0";
        }
    }

    //跳转首页
    @PostMapping("userinfo/index")
    public String index(HttpSession session) {
        String path = (String) session.getAttribute("path");
        if (path != null && path.contains("181225.zaisousuo.com/web") && !path.contains("181225.zaisousuo.com/web/userinfo/findpassword") && !path.contains("181225.zaisousuo.com/web/userinfo/register")) {
        /*if (path != null && path.contains("/ZaiSouSuo/web") && !path.contains("/ZaiSouSuo/web/userinfo/findpassword") && !path.contains("/ZaiSouSuo/web/userinfo/register")) {*/
            return "redirect:" + path;
        } else {
            return "redirect:/web/garbage/index";
        }
    }

    //发送邮件
    @GetMapping("userinfo/sendEmailCode")
    @ResponseBody
    public String sendtEmailCode(String email) {
        String messsge = "欢迎您注册再搜索，您的验证码是";
        String subject ="再搜索注册验证";
        String code = CodeUtil.inputEmail(email,messsge,subject);
        return code;
    }

    //发送手机验证码
    @ResponseBody
    @GetMapping("userinfo/sendPhoneCode")
    public String sendPhoneCode(String phoneNumber) {
        String code = CodeUtil.aliyun(phoneNumber);
        return code;
    }

    //判断邮箱是否注册
    @GetMapping("userinfo/checkEmail")
    @ResponseBody
    public String checkEmail(String email) {
        Userinfo userinfo = userinfoService.findByEmail(email);
        String f;
        if (userinfo == null) {
            f = "0";
        } else {
            f = "1";
        }
        return f;
    }

    //判断手机号是否注册
    @GetMapping("userinfo/checkPhone")
    @ResponseBody
    public String checkPhone(String phoneNumber) {
        Userinfo userinfo = userinfoService.findByPhone(phoneNumber);
        String f;
        if (userinfo == null) {
            f = "0";
        } else {
            f = "1";
        }
        return f;
    }

    //滑动图片验证
    @RequestMapping("userinfo/code")
    public void code() {
    }

    //个人信息页面
    @RequestMapping("usercenter/usPassport")
    public ModelAndView usPassport()
    {
        ModelAndView mv = new ModelAndView();
        List<City> provinces = cityService.findProvince();
        mv.addObject("provinces",provinces);
        return mv;
    }
    //我的回答
    @RequestMapping("usercenter/usAnswers")
    public void usAnswers() {
    }
    @RequestMapping("usercenter/answerList")
    @ResponseBody
    public ModelAndView answerList(HttpSession session,Integer pageNum) {
        if(pageNum==null)pageNum=1;

        ModelAndView modelAndView=new ModelAndView();
        Userinfo userinfo=(Userinfo) session.getAttribute("userinfo");
        PageInfo<Answer> pageInfo =answerService.findByUserId(userinfo.getId(),pageNum);

        modelAndView.addObject("pageInfo",pageInfo);
        return modelAndView;
    }
    //数据管理
    @RequestMapping("usercenter/usDate")
    public void usDate() {
    }
    //我提供的分类
    @RequestMapping("usercenter/usDatelist")
    @ModelAttribute("garbages")
    public List<Garbage> usDatelist(HttpSession session)
    {
        Userinfo userinfo = (Userinfo)session.getAttribute("userinfo");
        return garbageService.findByUserId(userinfo.getId());
    }
    //我的提问
    @RequestMapping("usercenter/usQuestions")
    public void usQuestion() {

    }
    @RequestMapping("usercenter/questionList")
    @ResponseBody
    public ModelAndView questionList(Integer pageNum,HttpSession session)
    {
        Userinfo userinfo = (Userinfo)session.getAttribute("userinfo");
        Integer id = userinfo.getId();
        if(pageNum==null) pageNum=1;
        ModelAndView mv = new ModelAndView();
        PageInfo<Question> pageInfo=questionService.findByUserId(pageNum,id);
        mv.addObject("pageInfo",pageInfo);
        return mv;
    }
    //我的文章
    @RequestMapping("usercenter/usArticle")
    public void usArticle() {}

    @RequestMapping("usercenter/articleList")
    public ModelAndView articleList(Integer pageNum,HttpSession session) {
        Userinfo userinfo = (Userinfo)session.getAttribute("userinfo");
        Integer id = userinfo.getId();
        if(pageNum==null) pageNum=1;
        ModelAndView mv = new ModelAndView();
        PageInfo<Article> pageInfo =  articleService.findById(pageNum,id);
        mv.addObject("pageinfo",pageInfo);
        return mv;
    }

    //退出
    @RequestMapping("userinfo/exit")
    public String exit(HttpServletResponse response, HttpServletRequest request) {
        request.getSession().removeAttribute("userinfo");
        CookieUtil.addCookie("phone_number", "", 0, response);
        CookieUtil.addCookie("email", "", 0, response);
        CookieUtil.addCookie("userpass", "", 0, response);
        String path = request.getHeader("referer");
        if (path != null) {
            System.out.println(path);
            return "redirect:" + path;
        } else {
            return "redirect:/web/garbage/index";
        }

    }

    //找回密码
    @RequestMapping("userinfo/findpassword")
    public void findPassword() {
    }

    @RequestMapping("userinfo/findpassword2")
    public void findPassword2() {
    }

    @RequestMapping("userinfo/findpassword3")
    public void findPassword3() {
    }

    @RequestMapping("userinfo/findpassword4")
    public void findPassword4() {
    }

    //找回密码验证手机号或者邮箱是否正确
    @PostMapping("userinfo/findpassword")
    @ResponseBody
    public String checkPasswordOrEmail(String username) {
        Userinfo userinfo = userinfoService.findPassword(username);
        if (userinfo == null) {
            return "0";
        } else {
            return "1";
        }
    }

    //发送验证码
    @GetMapping("userinfo/sendCode")
    public String sendCode(String username, HttpServletRequest request) {
        String code;
        String message ="您现在正在重置密码，您的验证码是";
        String subject = "再搜索重置密码";
        HttpSession session = request.getSession();
        if (username.contains("@")) {
            code = CodeUtil.inputEmail(username,message,subject);
        } else {
            code = CodeUtil.aliyun(username);
        }
        session.setAttribute("code", code);
        session.setAttribute("username", username);
        return "redirect:/web/userinfo/findpassword2";
    }

    //找回密码判断验证码
    @GetMapping("userinfo/checkCode")
    @ResponseBody
    public String checkCode(String code, HttpServletRequest request) {
        String codes = (String) request.getSession().getAttribute("code");
        if (code.equals(codes)) {
            return "1";
        } else {
            return "0";
        }
    }

    //重置密码
    @GetMapping("userinfo/resetPassword")
    public String resetPassword() {
        return "redirect:/web/userinfo/findpassword3";
    }

    //重置密码完成
    @PostMapping("userinfo/finish")
    public String finish(String password, HttpServletRequest request) {
        String username = (String) request.getSession().getAttribute("username");
        userinfoService.updatePassword(password, username);
        return "redirect:/web/userinfo/findpassword4";
    }
    //判断昵称是否重复
    @GetMapping("usercenter/checkNickname")
    @ResponseBody
    public String checkNickname(String nickname,HttpSession session)
    {
        Userinfo userinfo = userinfoService.checkNickname(nickname);

        if (userinfo!=null)
        {
            return"1";
        }
        else {
            Userinfo userinfo1 = (Userinfo) session.getAttribute("userinfo");
            userinfo1.setNickname(nickname);
            Integer id = userinfo1.getId();
            userinfoService.updateNickname(nickname,id);
            return "0";
        }
    }
   //修改邮箱
    @GetMapping("usercenter/updateEmail")
    public String updateEmail(String email,HttpSession session)
    {
        Userinfo userinfo = (Userinfo) session.getAttribute("userinfo");
        Integer id = userinfo.getId();
        userinfo.setEmail(email);
        userinfoService.updateEmail(email,id);
        return"redirect:/web/usercenter/usPassport";
    }
    //修改邮箱
    @GetMapping("usercenter/updatePhone")
    public String updatePhone(String phoneNumber,HttpSession session)
    {
        Userinfo userinfo = (Userinfo) session.getAttribute("userinfo");
        Integer id = userinfo.getId();
        userinfo.setPhoneNumber(phoneNumber);
        userinfoService.updatePhoneNumber(phoneNumber,id);
        return"redirect:/web/usercenter/usPassport";
    }
    //验证旧密码
    @GetMapping("usercenter/changePassword")
    @ResponseBody
    public String changePassword(String password,HttpSession session)
    {

        Userinfo userinfo=(Userinfo) session.getAttribute("userinfo");
        String password1 = userinfo.getPassword();
        if(password1.equals(MD5Utils.md5(password)))
        {
            return "1";
        }
        else
        {
            return "0";
        }
    }
    //修改密码
    @GetMapping("usercenter/modPassword")
    public  String modPassword(String password,HttpSession session)
    {
        Userinfo userinfo=(Userinfo) session.getAttribute("userinfo");
        Integer id = userinfo.getId();
        userinfoService.modPassword(MD5Utils.md5(password),id);
        session.removeAttribute("userinfo");
        return "redirect:/web/userinfo/login";
    }
    //修改头像
    @PostMapping("usercenter/updateHeadPic")
    public String updateHeadPic(MultipartFile file,HttpServletRequest request)
    {
        Userinfo userinfo = (Userinfo)request.getSession().getAttribute("userinfo");
        String ext = FilenameUtils.getExtension(file.getOriginalFilename());
        String fileName = UUID.randomUUID() + "." + ext;
        String realPath = request.getServletContext().getRealPath("/static/images") + "/" + fileName;
        try {
            file.transferTo(new File(realPath));
            userinfo.setHeadPic(fileName);
            userinfoService.updateHeadPic(userinfo);

        } catch (IOException e) {
        }
        return"redirect:/web/usercenter/usPassport";
    }
    //个人认证
    @RequestMapping("usercenter/checkVIP")
    @ResponseBody
    public void checkVIP(HttpSession session)
    {
        Userinfo userinfo = (Userinfo) session.getAttribute("userinfo");
        userinfoService.checkVip(userinfo);
        Userinfo userinfo1 = userinfoService.findById(userinfo.getId());
        userinfo.setVipChecked(userinfo1.getVipChecked());
        session.setAttribute("userinfo",userinfo);
    }
    //判断企业是否已被认证
    @GetMapping("usercenter/findCompanyName")
    @ResponseBody
    public String findCompanyName(String companyName)
    {
        CompanyApproval companyApproval = companyApprovalService.findCompanyName(companyName);
        if (companyApproval==null)
        {
            return "0";
        }
        else {
            return"1";
        }
    }
    //企业认证
    @PostMapping("usercenter/companyAuthenticat")
    public String company(CompanyApproval companyApproval,MultipartFile companyPicture,HttpServletRequest request)
    {
        String ext = FilenameUtils.getExtension(companyPicture.getOriginalFilename());
        String fileName = UUID.randomUUID() + "." + ext;
        String realPath = request.getServletContext().getRealPath("/static/images") + "/" + fileName;
        try {
            companyPicture.transferTo(new File(realPath));
        } catch (IOException e) {
        }
        companyApproval.setCompanyPic(fileName);
        companyApprovalService.companyAuthenticat(companyApproval,request.getSession());
        Integer id = companyApproval.getId();
        Userinfo userinfo = (Userinfo) request.getSession().getAttribute("userinfo");
        //companyApproval.setId(id);
       // userinfo.setCompanyApproval(companyApproval);
        userinfo.getCompanyApproval().setId(id);
        userinfo.getCompanyApproval().setCompanyChecked("1");
        return"redirect:/web/usercenter/usPassport";
    }
    //去往我的收藏页面
    @RequestMapping("/usercenter/usCollect")
    public void toUsCollect(){}

    //去往我的材质页面
    @RequestMapping("/usercenter/usTexture")
    public ModelAndView toUsTexture(HttpSession session ){
        Userinfo userinfo=(Userinfo)session.getAttribute("userinfo");
        Integer id=userinfo.getId();
        ModelAndView mv=new ModelAndView();
        mv.addObject("textures",textureService.findAllByUserId(id));
       return mv;
    }

    //去往collectData页面
    @RequestMapping("/usercenter/collectData")
    public ModelAndView toCollectData(HttpSession session){
        Userinfo userinfo = (Userinfo) session.getAttribute("userinfo");
        Integer userId = userinfo.getId();//获得登录用户id
        List<Article> articles = articleService.findCollectByUserId(userId);
        ModelAndView mv = new ModelAndView();
        mv.addObject("articles",articles);
        return mv;
    }

    /*开发团队*/
    @RequestMapping("/article/development")
    public void development()
    {}

    //关于我们
    @RequestMapping("/article/aboutUs")
    public void aboutUs(){}

}
